﻿using Architecture.CrossCutting.RepositoryPattern;
using Architecture.Domain.BankManagement.QuerySpecifications;
using Architecture.Domain.BankManagement.Repositories;
using Architecture.Domain.TestModel.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Architecture.Domain.BankManagement
{
    public class BankManagementServices : IDisposable
    {

        private CountriesRepository _countryRepository;
        private ClientsRepository _clientsRepository;


        public BankManagementServices(CountriesRepository countryRepository, ClientsRepository clientsRepository)
        {
            _countryRepository = countryRepository;
            _clientsRepository = clientsRepository;
        }


        public Country AddCountry(Country country)
        {
            //Check if country Id exist
            if (!country.Id.Equals(Guid.Empty))
            {
                throw new Exception("This country exists");
            }

            //Check if country already exist for the business Key
            if (_countryRepository.GetCountry(country.Name, country.CodeISO) != null)
            {
                throw new Exception("This country exists");
            }

            country.Id = Guid.NewGuid();
            _countryRepository.Add(country);
            _countryRepository.UnitOfWork.SaveChanges();

            return country;
        }


        public void CreateClient(Client client)
        {
            //Check if country Id exist
            if (!client.Id.Equals(Guid.Empty))
            {
                throw new Exception("This client exists");
            }

            if (client.Nationality == null)
            {
                throw new Exception("This Nationality is mandatory");
            }

            if (_countryRepository.Get(client.Nationality.Id) == null)
            {
                throw new Exception("This Country doesn't exist");
            }

            client.Id = Guid.NewGuid();
            _clientsRepository.Add(client);
            _clientsRepository.UnitOfWork.SaveChanges();

        }


        public Country GetCountry(String name)
        {
            return _countryRepository.AllMatching(CountriesSpecification.CountryByName(name)).SingleOrDefault();
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}
